package main

import (
	"fmt"
	"time"
)

//channel select
func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)
	sign := make(chan bool)
	stop := make(chan int)

	//10s之后发出关闭信号
	go func() {
		time.Sleep(3 * time.Second) //休息5s
		sign <- false
	}()
	//给ch1发出消息
	go func(s string) {
		ch1 <- s
		time.Sleep(1 * time.Second)
	}("one")
	//给ch2发出消息
	go func(s string) {
		ch2 <- s
		time.Sleep(2 * time.Second)
	}("tow")
	//select
	go func() {
		var m1, m2 string
		var chok bool
		fmt.Println("---- start ----")
		for {
			select {
			case m1, chok = <-ch1:
				if chok {
					fmt.Println("m1---", m1, chok)
				}
			case m2, chok = <-ch2:
				if chok {
					fmt.Println("m2---", m2, chok)
				}
			case chok = <-sign:
				if !chok {
					fmt.Println("End...", chok)
					//break
				}
			default:
				if !chok {
					fmt.Println("no message received")
				}
				//holding
			}
			if !chok {
				//退出主线程
				stop <- 0
				break //退出for{}
			}
		}
	}()
	fmt.Println("Exit:", <-stop)

	//close在元素出队之后再执行
	que := make(chan int, 2)
	que <- 1
	que <- 2
	close(que)

	for q := range que {
		fmt.Println(q)
	}
}
